<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class myBasket implements Countable{
    private $bucketProduct = 'bucket_product_';
    private $productCount = 'bucket_count_';
    private $elements = array();
    private $value;
    
    private function findFreeId(){
        $i = 1;
        while(true){
            if(!isset($_SESSION[$this->bucketProduct . $i])){
                return $i;
            }
            $i++;
        }
    }
    
    public static function getInstance(){
        static $instance;
        if(!isset($instance)){
            $instance = new self();
        }
        return $instance;
    }
    
    public function addItem($product_id, $product_count){
        $id = $this->findFreeId();
        $_SESSION[$this->bucketProduct . $id] = $product_id;
        $_SESSION[$this->productCount . $id] = $product_count;
        $item =  new BasketItem($id, $product_id, $product_count);
        $this->value = $item->getProduct()->getPrice() * $item->getCount();
        $this->elements[] = $item;
    }
    
    public function toArray(){
        return $this->elements;
    }
    
    public function deleteProduct($id){
        if(isset($_SESSION[$this->bucketProduct . $id])){
            unset($_SESSION[$this->bucketProduct . $id]);
            unset($_SESSION[$this->productCount . $id]);
            return true;
        }
        return false;
    }
    
    public function getProduct($id){
        foreach($this->elements as $element){
            if($element->getOwnId() == $id){
                return $element;
            }
        }
        return NULL;
    }
    
    public function count(){
        return count($this->elements);
    }
}